package com.ws.gold.swing;

import com.alibaba.fastjson2.JSONObject;
import com.ws.gold.service.RealtimeGoldPriceService;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ChartWindow extends JFrame {

    private final RealtimeGoldPriceService service;

    private final LineChartPanel chartPanel;

    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    public ChartWindow(RealtimeGoldPriceService service) {
        this.service = service;
        setTitle("实时刷新折线图");
        setSize(900, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        chartPanel = new LineChartPanel(service.getChartData().getList("xLabels", String.class), service.getChartData().getList("yValues", Double.class));

        JButton refreshBtn = new JButton("手动刷新");
        refreshBtn.addActionListener(e -> refreshData());

        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        topPanel.add(refreshBtn);

        add(topPanel, BorderLayout.NORTH);
        add(chartPanel, BorderLayout.CENTER);

        scheduler.scheduleAtFixedRate(this::refreshData, 0, 10, TimeUnit.SECONDS);
    }

    private void refreshData() {
        //查询前先入库最新数据
        service.getLatestGoldPrice();

        JSONObject chartData = service.getChartData();
        List<String> x = chartData.getList("xLabels", String.class);
        List<Double> y = chartData.getList("yValues", Double.class);
        chartPanel.updateData(x, y);
    }

}
